﻿using System;
using System.Windows;
using Utils.Wpf;

namespace StockAnalyst2.Options
{
	internal class OptionsManager
	{
		#region Properties

		public ApplicationOptions EffectiveSettings { get; private set; }
		
		#endregion

		#region Events

		public event EventHandler<DialogShowRequestedEventArgs> DialogShowRequested;

		#endregion

		#region Public Methods

		public OptionsManager()
		{
			DataBaseChecker checker = new DataBaseChecker(Properties.Settings.Default.DatabaseServer, Properties.Settings.Default.DatabaseName);
			
			if (!checker.IsDataBaseServerAvailable() || !checker.IsDataBaseAvailable() || !checker.IsDataBaseStructureValid())
			{
				this.ShowOptionsWithoutMainWindow();
			}

			this.EffectiveSettings = ApplicationOptionsDataSource.Load();
		}

		public void ShowOptionsWithMainWindow()
		{
			using (OptionsDialog optionsDialog = new OptionsDialog())
			{
				optionsDialog.DataContext = new OptionsVM(ApplicationOptionsDataSource.Load());

				DialogShowRequestedEventArgs eventArgs = new DialogShowRequestedEventArgs(optionsDialog);
				this.OnDialogShowRequired(eventArgs);
				bool? dialogResult = eventArgs.DialogResult;

				if (dialogResult != null && dialogResult.Value && optionsDialog.DataContext.DataChanged)
				{
					MessageBox.Show("The application must be restarted to apply the required changes", "Restart required", MessageBoxButton.OK, MessageBoxImage.Exclamation);
				}

			}
		}

		protected virtual void OnDialogShowRequired(DialogShowRequestedEventArgs e)
		{
			if (this.DialogShowRequested != null)
			{
				this.DialogShowRequested(this, e);
			}
		}

		#endregion

		#region Private Methods

		private void ShowOptionsWithoutMainWindow()
		{
			using (OptionsDialog optionsDialog = new OptionsDialog())
			{
				optionsDialog.DataContext = new OptionsVM(ApplicationOptionsDataSource.Load());
				optionsDialog.ShowInTaskbar = true;
				optionsDialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;

				bool? dialogResult = optionsDialog.ShowDialog();
				if (dialogResult == null || !dialogResult.Value)
				{
					Environment.Exit(-1);
				}
			}
		}

		#endregion

	}
}
